package com.ques.controller;

import com.alibaba.excel.EasyExcel;
import com.ques.entity.DeleteParam;
import com.ques.entity.QueryParam;
import com.ques.pojo.Option;
import com.ques.pojo.Question;
import com.ques.pojo.QuestionAnswer;
import com.ques.service.AnswerService;
import com.ques.service.QuestionService;
import com.ques.utils.BasicMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zq  2020-02-10
 */
@RestController
@RequestMapping("/api")
public class AnswerRestController {

//    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss");

    @Autowired
    AnswerService answerService;
    @Autowired
    QuestionService questionService;

    /**
     * @return
     */
    @PostMapping("/getAllAnswer")
    public BasicMessage getAllAnswer(@RequestBody QueryParam queryParam) {
        if(queryParam == null || StringUtils.isEmpty(queryParam.getId() )   ){
            return BasicMessage.fail().putmessage("message", "问卷不存在");
        }

        Question question = questionService.getQuestionById( queryParam.getId() );
        List<Option> subject = question.getSubject();

        if (subject == null) {
            return BasicMessage.fail().putmessage("message", "问卷不存在");
        }
        List<Map<String, String>> title = convertToMap(subject);

        System.out.println(title);
        List<QuestionAnswer> answers = answerService.getAllAnswerPage( queryParam );
        return BasicMessage.success().putmessage("data", answers).putmessage("title", title).putmessage("total",queryParam.getTotal());
    }

    private List<Map<String, String>> convertToMap(List<Option> subject) {
        List<Map<String, String>> title = new ArrayList<>(subject.size());
        // 准备表头
        for (int i = 0; i < subject.size(); i++) {
            Option option = subject.get(i);
            HashMap<String, String> t = new HashMap<>(2);
            t.put("lable", option.getTitle());
            t.put("prop", i + "");
            title.add(t);
        }
        return title;
    }

    @PostMapping("/deleteAnswer")
    public BasicMessage deleteAnswer(@RequestBody DeleteParam deleteParam) {
        if (StringUtils.isEmpty(deleteParam.getQuestionId())) {
            return BasicMessage.fail().putmessage("message", "数据表为空");
        }
        if (deleteParam.getAnswerIds().size() == 0) {
            return BasicMessage.fail().putmessage("message", "待删除数据为空");
        }
        long flag = answerService.deleteAnswer(deleteParam.getQuestionId(), deleteParam.getAnswerIds());
        if (flag > 0) {
            return BasicMessage.success().putmessage("message", "成功删除 " + flag + " 条数据");
        } else {
            return BasicMessage.fail().putmessage("message", "删除失败，请稍后重试");
        }
    }

    @PostMapping("/downExcel/{questionId}")
    public void downAnswerExcel(@PathVariable String questionId , HttpServletResponse response) throws IOException {

        Question question = questionService.getQuestionById(questionId);
        List<Map<String, String>> maps = convertToMap(question.getSubject());
        List<QuestionAnswer> answers = answerService.getAllAnswer(questionId);
        // 数据转换
        List<List<String>> head = head(maps);

        List<List<Object>> lists = dataList(head.size(), answers);
        System.out.println(head);
        System.out.println(lists);
//        String fileName = AnswerRestController.class.getResource("/").getPath() + System.currentTimeMillis() + ".xlsx";
        String title = question.getTitle();
        // 名字保留20 个字符以内
        if(title.length() > 15){
            title = title.substring(0,15) ;
        }
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URL Encoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(title, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        System.out.println(fileName);
        EasyExcel.write(response.getOutputStream()).head(head).sheet(fileName).doWrite(lists);
    }
    private List<List<String>> head(List<Map<String, String>> maps) {
        List<List<String>> list = new ArrayList<>();
        for (Map<String, String> map : maps) {
            ArrayList<String> head = new ArrayList<>(1);
            head.add(map.get("lable"));
            list.add(head);
        }
        return list;
    }

    /**
     * @param colCount  表示题 的 个数
     * @param answers 所有答案
     * @return 返回 插入 表格的数据
     */
    private List<List<Object>> dataList(int colCount, List<QuestionAnswer> answers) {
        List<List<Object>> list = new ArrayList<List<Object>>();
        // 答案 的 条数
        int rowCount = answers.size();
        for (int row = 0; row < rowCount; row++) {
            // 存放的 数据
            List<Object> rowData = new ArrayList<>(colCount);
            // 获取一条数据
            QuestionAnswer rowAnswer = answers.get(row);
            // 先保证数据不为空
            if (rowAnswer != null) {
                //  所有  列数据
                Map<String, List<String>> colAnswer = rowAnswer.getAnswer();
                for (int col = 0; col < colCount; col++) {
                    // 答案的个数
                    List<String> strings = colAnswer.get(col+"");
                    //
                    if (strings == null || strings.size() == 0) {
                        rowData.add(col, "未做答");
                    } else if (strings.size() == 1) {
                        //单选
                        rowData.add(col, strings.get(0));
                    } else {
                        // 多选 字符串 进行 拼接
                        StringBuilder stringBuilder = new StringBuilder();
                        for (int z = 0; z < strings.size(); z++) {
                            stringBuilder.append(z + 1);
                            stringBuilder.append("、");
                            stringBuilder.append(strings.get(z));
                            stringBuilder.append("\n");
                        }
                        rowData.add(col, stringBuilder.toString());
                    }
                }
            }
            list.add(rowData);
        }
        return list;
    }
}
